package com.demo.excel;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.demo.eneity.User;
import com.demo.mapper.UserMapper;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Getter
@Setter
@Component
@Slf4j
public class CutDataListener extends AnalysisEventListener<User> {

    private List<User> list = new ArrayList<>();

    public CutDataListener() {

    }

    @Override
    public void invoke(User user, AnalysisContext analysisContext) {
        if (user != null) {
            list.add(user);
        }
        //分批插入，大于10w执行一次
        if(list.size() >= 100000) {
            saveData();
            list.clear();
        }
    }


    /**
     * 保存数据到db
     */
    private void saveData() {
        UserMapper userMapper = SpringUtil.getBean(UserMapper.class);
        userMapper.insertBatchSomeColumn(list);
        list.clear();
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        list.clear();
    }
}
